package com.smarthospital.service.impl;

import com.smarthospital.common.Result.CodeMsg;
import com.smarthospital.common.Result.CommonException;
import com.smarthospital.dao.daoService.HospitalDaoService;
import com.smarthospital.dao.daoService.ReportDaoService;
import com.smarthospital.entity.pojo.Hospital;
import com.smarthospital.entity.pojo.Report;
import com.smarthospital.entity.pojo.User;
import com.smarthospital.service.ReportGeter;
import com.smarthospital.service.ReportGetetContext;
import com.smarthospital.service.ReportService;
import com.smarthospital.web.inteceptor.LoginInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * create by sym  2021/5/4 16:30.
 */
@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportDaoService reportDaoService;

    @Autowired
    private ReportGetetContext reportGetetContext;
    @Override
    public Map<String, List<Report>> querMyReports() {
        User user = LoginInterceptor.getUser();
        List<Report> list = reportDaoService.querMyReports(user.getId()+"");
        return  list.stream().collect(Collectors.groupingBy(Report::getHospital));

    }

    @Autowired
    private HospitalDaoService hospitalDaoService;
    /**
     * 根据医院id拉取报告
     * @param hospitalId
     * @return
     */
    @Override
    public Map<String, List<Report>> getReportByHos(Long hospitalId) {
        //默认去拉取
        Hospital hospital = hospitalDaoService.queryById(hospitalId);
        if (hospital == null) {
            throw  new CommonException(CodeMsg.ERROR_NOT_HOSPITAL);
        }
        ReportGeter reportGeter = reportGetetContext.getReportGeter(hospital.getHospitalCode());
        User user = LoginInterceptor.getUser();
        if (null != reportGeter) {
            //将数据组装为标准格式
            List<Report> list = reportGeter.getReportFromHospital(user);
            //根据报告id确认数据是否重复
            List<Report> dbList = reportDaoService.selectByHospitalAndReportId(user.getId(),list);
            //没重复的插入数据库
            List<Report> collect = list.stream().filter(report -> dbList.stream().noneMatch(dbr -> (dbr.getHospital().equals(report.getHospital())) && dbr.getReportId().equals(report.getReportId()))).collect(Collectors.toList());

            for (Report report : collect) {
                reportDaoService.insertSelective(report);
            }
        }else {
            log.error("【拉取医院报告】 不支持查询 "+hospital.getHospitalName()+" 的报告");
        }

        List<Report> allList = reportDaoService.selectByHospitalAndUserId(hospital.getHospitalName(),user.getId());
        Map<String, List<Report>> listMap = allList.stream().collect(Collectors.groupingBy(Report::getHospital));
        //返回标准格式数据
        return listMap;
    }
}
